from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import random
import time
from selenium.common.exceptions import TimeoutException, NoSuchElementException, StaleElementReferenceException
from lxml import etree


class SeleniumCommon():
    def GetObjUntilExist(self,driver,  xpath, timeOut=5, timeSpan=0.5):
        locator = (By.XPATH, xpath)
        WebDriverWait(driver, timeout=timeOut, poll_frequency=timeSpan).until(EC.presence_of_element_located(locator))
        return  driver.find_element_by_xpath(xpath);

    def GetObjListUntilExist(self,driver,  xpath, timeOut=5, timeSpan=0.5):
        locator = (By.XPATH, xpath)
        WebDriverWait(driver, timeout=timeOut, poll_frequency=timeSpan).until(EC.presence_of_all_elements_located(locator))
        return  driver.find_elements_by_xpath(xpath);

    def GetObjUntilVisual(self,driver,  xpath, timeOut=5, timeSpan=0.5):
        locator = (By.XPATH, xpath)
        WebDriverWait(driver, timeout=timeOut, poll_frequency=timeSpan, ignored_exceptions = StaleElementReferenceException).until(EC.visibility_of_element_located(locator))
        return  driver.find_element_by_xpath(xpath);

    def GetObjListUntilVisual(self,driver,  xpath, timeOut=5, timeSpan=0.5):
        locator = (By.XPATH, xpath)
        WebDriverWait(driver, timeout=timeOut, poll_frequency=timeSpan, ignored_exceptions = StaleElementReferenceException).until(EC.visibility_of_any_elements_located(locator))
        return  driver.find_elements_by_xpath(xpath);

    '''
    def WaitObjUntilNotExist(self,driver,  xpath, timeOut=5, timeSpan=0.5):
        timeEnd = time.time() + timeOut
        while True:
            dom = etree.HTML(driver.page_source)
            a = dom.xpath(xpath)
            if len(a) == 0:
                break
            time.sleep(timeSpan)
            if timeEnd < time.time():
                raise TimeoutException()
    '''

    def WaitObjUntilNotExist(self,driver,  xpath, timeOut=5, timeSpan=0.5):
        locator = (By.XPATH, xpath)
        WebDriverWait(driver, timeOut, timeSpan).until_not(EC.presence_of_element_located(locator))

    def WaitObjUntilExist(self,driver,  xpath, timeOut=5, timeSpan=0.5):
        locator = (By.XPATH, xpath)
        WebDriverWait(driver, timeOut, timeSpan).until(EC.presence_of_element_located(locator))

    def WaitObjUntilValueNotEmpty(self,elem, timeOut=5, timeSpan=0.5):
        timeEnd = time.time() + timeOut
        while True:
            s= elem.get_attribute("value")
            if len(s) != 0:
                break
            time.sleep(timeSpan)
            if timeEnd < time.time():
                raise TimeoutException()

